package day20210705;

import treenode.SimpleTreeNode;

/**
 * 530. 二叉搜索树的最小绝对差
 *
 * @author lizy
 * @date 2021/07/05
 */
public class Solution2 {

    public static void main(String[] args) {
        Solution2 solution = new Solution2();
        SimpleTreeNode simpleTreeNode = new SimpleTreeNode();
        simpleTreeNode.val = 6;
        simpleTreeNode.right = new SimpleTreeNode(8);
        simpleTreeNode.right.right = new SimpleTreeNode(9);
        simpleTreeNode.right.left = new SimpleTreeNode(7);
        simpleTreeNode.left = new SimpleTreeNode(2);
        simpleTreeNode.left.left = new SimpleTreeNode(1);
        System.out.println("=================================");
        System.out.println(solution.getMinimumDifference(simpleTreeNode));
        System.out.println("=================================");
    }

    int pre;
    int ans;

    public int getMinimumDifference(SimpleTreeNode root) {
        ans = Integer.MAX_VALUE;
        pre = -1;
        dfs(root);
        return ans;
    }

    public void dfs(SimpleTreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        if (pre == -1) {
            pre = root.val;
        } else {
            ans = Math.min(ans, root.val - pre);
            pre = root.val;
        }
        dfs(root.right);
    }
}
